# Builds our docker bake file
inputs:
  push-to-dockerhub:
    description: "Whether to push to Dockerhub as well as ECR"
    required: false
    default: false

runs:
  using: 'composite'
  steps:
    # Get clean environment variables via https://github.com/marketplace/actions/github-environment-variables-action
    - uses: FranzDiebold/github-env-vars-action@v2
    - name: Set up Docker Buildx
      uses: docker/setup-buildx-action@v3
    - name: Login to Amazon ECR
      uses: aws-actions/amazon-ecr-login@v1
    - name: Build and push
      shell: bash
      run: |
        # Configure our buildkit builders
        docker buildx create --name remote-buildkit-agent --node mdb_amd64 --platform linux/amd64 --driver=remote --use tcp://remote-buildkit-agent.infrastructure.svc.cluster.local:80 || true # Create the builder (might already exist)
        docker buildx create --name=remote-buildkit-agent --node mdb_arm64 --platform linux/arm64 --append --driver=remote --use tcp://remote-buildkit-agent-arm.infrastructure.svc.cluster.local:80 || true # Same for ARM

        # Build amd64 and arm64 images in parallel and wait for both to finish
        VERSION=${{ env.CI_SHA }} BRANCH=${{ env.CI_ACTION_REF_NAME }} PUSH_TO_DOCKERHUB=${{ inputs.push-to-dockerhub }} PLATFORM=linux/amd64 docker buildx bake --progress plain --push -f docker/docker-bake.hcl &
        VERSION=${{ env.CI_SHA }} BRANCH=${{ env.CI_ACTION_REF_NAME }} PUSH_TO_DOCKERHUB=${{ inputs.push-to-dockerhub }} PLATFORM=linux/arm64 docker buildx bake --progress plain --push -f docker/docker-bake.hcl &
        wait

        # Create multi-arch manifests
        VERSION=${{ env.CI_SHA }} BRANCH=${{ env.CI_ACTION_REF_NAME }} PLATFORM="" docker buildx bake -f docker/docker-bake.hcl --print | jq '.target[] | .tags[]' | xargs -I'{}' docker buildx imagetools create -t '{}' '{}-amd64' '{}-arm64'
